<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <sticky :z-index="10" :class-name="'sub-navbar ' + postForm.status">
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">确认发布</el-button>
        <el-button v-loading="loading" type="warning" @click="$router.go(-1)">返回</el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-form-item label="选择分类">
          <el-select v-model="postForm.cateId" placeholder="上级分类">
            <el-option label="顶级分类" value="0" />
            <el-option v-for="(item, index) in list" :key="index" :label="item.title" :value="item.id" v-html="item.title_show" />
          </el-select>
        </el-form-item>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="文章标题" prop="title">
          <el-input v-model="postForm.title" :rows="1" type="textarea" class="article-textarea" autosize placeholder="请输入文章标题" />
        </el-form-item>

        <!--        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="封面图片" prop="title">
          <Upload v-model="postForm.img" />
        </el-form-item> -->

        <el-form-item label="Logo" label-width="100px">
          <el-upload class="avatar-uploader" action="http://up-z0.qiniup.com" :show-file-list="false" :on-success="handleAvatarSuccess"
            :data="{ token: qiniu.token }">
            点击更换
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item prop="content" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="postForm.content" :height="400" />
        </el-form-item>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="文章排序">
          <el-input v-model="postForm.sort" :rows="1" type="textarea" class="article-textarea" autosize placeholder="请输入文章排序" />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
  import Tinymce from '@/components/Tinymce';
  import Upload from '@/components/Upload/SingleImage3'
  import MDinput from '@/components/MDinput';
  import Sticky from '@/components/Sticky'; // 粘性header组件
  import {
    validURL
  } from '@/utils/validate';
  import {
    fetchArticle
  } from '@/api/article';
  import {
    searchUser
  } from '@/api/remote-search';
  import Warning from './Warning';
  import {
    CommentDropdown,
    PlatformDropdown,
    SourceUrlDropdown
  } from './Dropdown';
  import {
    getCate,
    addArticle,
    getArticle,
    updateArticle
  } from '@/api/article';
  import {
    getQiniuToken
  } from '@/api/qiniu'
  import {
    dateHandle,
    qiniuToken
  } from '@/api/dateHandle';
  const defaultForm = {
    status: 'draft', // 头部发布背景灰色
    title: '', // 文章题目
    content: '', // 文章内容
    content_short: '', // 文章摘要
    sort: 10, // 文章排序
    cateId: null,

  };

  export default {
    name: 'ArticleDetail',
    components: {
      Tinymce,
      MDinput,
      Upload,
      Sticky,
      Warning,
      CommentDropdown,
      PlatformDropdown,
      SourceUrlDropdown
    },
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      const validateRequire = (rule, value, callback) => {
        if (value === '') {
          this.$message({
            message: rule.field + '为必传项',
            type: 'error'
          });
          callback(new Error(rule.field + '为必传项'));
        } else {
          callback();
        }
      };
      return {
        imageUrl: "",
        qiniu: {},
        list: null,
        listQuery: null,
        postForm: Object.assign({}, defaultForm),
        loading: false,
        userListOptions: [],
        img: '',
        rules: {
          title: [{
            validator: validateRequire
          }],
          content: [{
            validator: validateRequire
          }]
        },
        tempRoute: {},
        id: 0
      };
    },

    created() {
      this.getList();
      if (this.$route.params.Id) {
        this.id = this.$route.params.Id;
        this.getArticle(this.id);
      }
      this.qiniuGet();
      console.log(this.qiniu);
      console.log(this.postForm);
      
    },

    methods: {
      qiniuGet() {
        qiniuToken().then(res => {
          console.log(res.data);
          this.qiniu = res.data
          console.log(this.qiniu);
          this.imageUrl = this.qiniu.domain + this.postForm.img;
        });
      },
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        this.postForm.img = res.key;
      },
      submitForm() {
        this.$refs.postForm.validate(valid => {
          if (valid) {
            if (this.id) {
              const param = {
                id: this.id,
                cateId: this.postForm.cateId,
                title: this.postForm.title,
                content: this.postForm.content,
                sort: this.postForm.sort,
                img: this.postForm.img
              };
              updateArticle(param).then(res => {
                if (res.code == 20000) {
                  this.loading = true;
                  this.$notify({
                    title: '成功',
                    message: '编辑文章成功',
                    type: 'success',
                    duration: 2000
                  });
                  this.postForm.status = 'published';
                  this.loading = false;
                  this.$router.push({
                    name: 'articleList'
                  });
                } else {
                  console.log('error submit!!');
                  return false;
                }
              });
            } else {
              addArticle(this.postForm).then(res => {
                if (res.code == 20000) {
                  this.loading = true;
                  this.$notify({
                    title: '成功',
                    message: '发布文章成功',
                    type: 'success',
                    duration: 2000
                  });
                  this.postForm.status = 'published';
                  this.loading = false;
                  this.$router.push({
                    name: 'articleList'
                  });
                } else {
                  console.log('error submit!!');
                  return false;
                }
              });
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

      //获取分类
      getList() {
        this.loading = true;
        getCate(this.listQuery).then(res => {
          if (res.code == 20000) {
            this.list = res.data;
            setTimeout(() => {
              this.loading = false;
            }, 0.3 * 1000);
          }
        });
      },

      getArticle(id) {
        getArticle({
          id: id
        }).then(res => {
          if (res.code == 20000) {
            this.postForm.title = res.data.Title;
            this.postForm.content = res.data.Content;
            this.postForm.Sort = res.data.Sort;
            this.postForm.cateId = Number(res.data.Cateid);
            this.postForm.img = res.data.Img;
          }
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  @import '~@/styles/mixin.scss';

  .createPost-container {
    position: relative;

    .createPost-main-container {
      padding: 40px 45px 20px 50px;

      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;

        .postInfo-container-item {
          float: left;
        }
      }
    }

    .word-counter {
      width: 40px;
      position: absolute;
      right: 10px;
      top: 0px;
    }
  }

  .article-textarea /deep/ {
    textarea {
      padding-right: 40px;
      resize: none;
      border: none;
      border-radius: 0px;
      border-bottom: 1px solid #bfcbd9;
    }
  }

  .avatar-uploader .el-upload {
    margin-left: 20px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 200px;
    height: 250px;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 198px;
    height: 198px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 190px;
    height: 190px;
    display: block;
  }
</style>
